<?php
namespace App\Http\Controllers\v1;

use Illuminate\Http\Request;
use Mockery\Exception;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use App\Http\Controllers\RequestBackController;
use App\Http\Controllers\Controller;
use App\Http\Controllers\CheckController;
use App\Http\Controllers\ToolController;


class PurviewController extends Controller
{
    /***查询用户权限可操作菜单项
     * @param
     * post         UserId           用户ID（若无则查询当前用户）
     * @return array
     */
    public function MenuList($request)
    {
        if(!CheckController::CheckUser($request))
        {
            return RequestBackController::Structure(205);
        }
        $pos=$request->all();
        if(CheckController::CheckParameter($pos,['UserId']))
        {
            $user=DB::table('yl_user')->where('user_id',$pos['UserId'])->first();
            $_purview_id=$user->purview_id;
        }
        else
        {
            $redis = app('redis.connection');
            $UserLogin=$request->header('UserLogin')?$request->header('UserLogin'):'';
            $GroupId=$request->header('GroupId')?$request->header('GroupId'):'';
            $_purview_id=$redis->GET($UserLogin.'G'.$GroupId.'_purview');
        }
        $id_array=DB::table('yl_purview')->where('purview_id',$_purview_id)->first();
        $_personal=!empty($id_array->purview_personal)?explode(',',$id_array->purview_personal):array();
        $_all=!empty($id_array->purview_all)?explode(',',$id_array->purview_all):array();
        $_menu_id_array=array_merge($_all,$_personal);
        $_menu_res=DB::table('yl_menu')->select('menu_id as MenuId','menu_name as MenuName','menu_fid as MenuFid','menu_route as MenuRoute')->whereIn('menu_id',$_menu_id_array)->get()->map(function($val){return $val=(array)$val;})->keyBy(function($item){return $item['MenuId'];})->toArray();
        $ToolController=new ToolController();
        $_menu_res=$ToolController->ListClassified($_menu_res,0,'MenuFid','MenuId');
        return RequestBackController::Structure(101,$_menu_res);
    }
    /***查询用户权限可显示的权限组列表
     * @param
     * post         MenuId           菜单id
     * @return array
     */
    public function PurviewList($request)
    {
        if(!CheckController::CheckUser($request))
        {
            return RequestBackController::Structure(205);
        }
        $pos=$request->all();
        if(!CheckController::CheckParameter($pos,['MenuId']))
        {
            return RequestBackController::Structure(502);
        }
        if($this->PurviewVerdict($request,$pos['MenuId'])=='None')
        {
            return RequestBackController::Structure(504);
        }
        elseif($this->PurviewVerdict($request,$pos['MenuId'])=='All')
        {
            $res=DB::table('yl_purview')->select('purview_id as PurviewId','purview_name as PurviewName','edit_able as EditAble')->get();
        }
        else
        {
            $UserLogin=$request->header('UserLogin')?$request->header('UserLogin'):'';
            $res=DB::table('yl_user')->join('yl_purview','yl_user.purview_id','=','yl_purview.purview_id')->where('yl_user.user_login',$UserLogin)->select('yl_purview.purview_id as PurviewId','yl_purview.purview_name as PurviewName','yl_purview.edit_able as EditAble')->get();
        }
        return RequestBackController::Structure(101,$res);
    }
    /***新增或修改权限信息
     * @param
     * post         MenuId           菜单id
     * post         PurviewId        权限id（有的话为修改，没有就是增加）
     * @return array
     */
    public function UpdatePurview($request)
    {
        if(!CheckController::CheckUser($request))
        {
            return RequestBackController::Structure(205);
        }
        $pos=$request->all();
        if(!CheckController::CheckParameter($pos,['MenuId']))
        {
            return RequestBackController::Structure(502);
        }
        if($this->PurviewVerdict($request,$pos['MenuId'])!='All')
        {
            return RequestBackController::Structure(503);
        }
        else
        {
            $arr=['purview_personal'=>'','purview_all'=>''];
            if(isset($pos['PurviewName']))
                $arr['purview_name']=$pos['PurviewName'];
            if(isset($pos['PersonPurview']))
                $arr['purview_personal']=$pos['PersonPurview'];
            if(isset($pos['PurviewAll']))
                $arr['purview_all']=$pos['PurviewAll'];
            if(CheckController::CheckParameter($pos,['PurviewId']))
            {
                DB::table('yl_purview')->where('purview_id',$pos['PurviewId'])->update($arr);
            }
            else
            {
                DB::table('yl_purview')->insert($arr);
            }
            return RequestBackController::Structure(101);
        }
    }
    public function PurviewMenuList($request)
    {
        if(!CheckController::CheckUser($request))
        {
            return RequestBackController::Structure(205);
        }
        $pos=$request->all();
        if(!CheckController::CheckParameter($pos,['MenuId','PurviewId']))
        {
            return RequestBackController::Structure(502);
        }
        if($this->PurviewVerdict($request,$pos['MenuId'])!='All')
        {
            return RequestBackController::Structure(503);
        }
        else
        {
            $purview=DB::table('yl_purview')->where('purview_id',$pos['PurviewId'])->first();
            $_all=explode(',',$purview->purview_all);
            $_personal=explode(',',$purview->purview_personal);

            $_menu_res=DB::table('yl_menu')->select('menu_id as MenuId','menu_name as MenuName','menu_fid as MenuFid','menu_route as MenuRoute')->get()->map(function($val){$val->Type='None';return $val=(array)$val;})->keyBy(function($item){return $item['MenuId'];})->toArray();
            $ToolController=new ToolController();
            foreach($_all as $k=>$v)
            {
                if(!empty($v))
                $_menu_res[$v]['Type']='All';
            }
            foreach($_personal as $k=>$v)
            {
                if(!empty($v))
                $_menu_res[$v]['Type']='Personal';
            }
            $_menu_res=$ToolController->ListClassified($_menu_res,0,'MenuFid','MenuId');
            return RequestBackController::Structure(101,$_menu_res);
        }
    }
    /***删除权限信息
     * @param
     * post         MenuId           菜单id
     * post         PurviewId        权限id
     * @return array
     */
    public function DeletePurview($request)
    {
        if(!CheckController::CheckUser($request))
        {
            return RequestBackController::Structure(205);
        }
        $pos=$request->all();
        if(!CheckController::CheckParameter($pos,['MenuId','PurviewId']))
        {
            return RequestBackController::Structure(502);
        }
        if($this->PurviewVerdict($request,$pos['MenuId'])!='All')
        {
            return RequestBackController::Structure(503);
        }
        else
        {
            DB::table('yl_purview')->where('purview_id',$pos['PurviewId'])->where('edit_able',1)->delete();
            return RequestBackController::Structure(101);
        }
    }
//    public function UserAble($request)
//    {
//        if(!CheckController::CheckUser($request))
//        {
//            return RequestBackController::Structure(205);
//        }
//        $pos=$request->all();
//        if(!CheckController::CheckParameter($pos,['MenuId','TargetId','UserAble']))
//        {
//            return RequestBackController::Structure(502);
//        }
//        if($this->PurviewVerdict($request,$pos['MenuId'])!='All')
//        {
//            return RequestBackController::Structure(503);
//        }
//        else
//        {
//            $userAble=$pos['UserAble']==1||$pos['UserAble']==0?$pos['UserAble']:0;
//            DB::table('yl_user')->where('id',$pos['TargetId'])->update(['user_able'=>$userAble]);
//            return RequestBackController::Structure(101);
//        }
//    }
    public function UserPurview($request)
    {
        if(!CheckController::CheckUser($request))
        {
            return RequestBackController::Structure(205);
        }
        $pos=$request->all();
        if(!CheckController::CheckParameter($pos,['MenuId','UserName','UserMobile','PurviewId','GroupId','UserAble']))
        {
            return RequestBackController::Structure(502);
        }
        if($this->PurviewVerdict($request,$pos['MenuId'])!='All')
        {
            return RequestBackController::Structure(503);
        }
        else
        {
            $arr=[
                'user_name'=>$pos['UserName'],
                'user_mobile'=>$pos['UserMobile'],
                'purview_id'=>$pos['PurviewId'],
                'group_id'=>$pos['GroupId'],
                'user_able'=>$pos['UserAble']
            ];
            if(isset($pos['PassWord'])&&!empty($pos['PassWord']))
            {
                $arr['user_password']=base64_encode($pos['PassWord']);
            }
            if(isset($pos['TargetId']))
            {
                DB::table('yl_user')->where('user_id',$pos['TargetId'])->update($arr);
            }
            else
            {
                DB::table('yl_user')->insert($arr);
            }

            return RequestBackController::Structure(101);
        }
    }
    public function UserDelete($request)
    {
        if(!CheckController::CheckUser($request))
        {
            return RequestBackController::Structure(205);
        }
        $pos=$request->all();
        if(!CheckController::CheckParameter($pos,['MenuId','TargetId']))
        {
            return RequestBackController::Structure(502);
        }
        if($this->PurviewVerdict($request,$pos['MenuId'])!='All')
        {
            return RequestBackController::Structure(503);
        }
        DB::table('yl_user')->where('user_id',$pos['TargetId'])->delete();
        return RequestBackController::Structure(101);
    }


    public function PurviewVerdict($request,$menu_id)
    {
        return $this->AllPurview($request,$menu_id)?'All':($this->PersonalPurview($request,$menu_id)?'Personal':'None');
    }

    /***查询用户  某菜单对应个人查看权限
     * @param
     * @return array
     */
    protected function PersonalPurview($request,$menu_id)
    {
        $redis = app('redis.connection');
        $UserLogin=$request->header('UserLogin')?$request->header('UserLogin'):'';
        $GroupId=$request->header('GroupId')?$request->header('GroupId'):'';
        $_purview_id=$redis->GET($UserLogin.'G'.$GroupId.'_purview');
        $res=DB::table('yl_purview')->whereRaw("FIND_IN_SET($menu_id,purview_personal)")->where('purview_id',$_purview_id)->first();
        return isset($res->purview_id)?true:false;
    }

    /***查询用户  某菜单对应全体查看权限
     * @param
     * @return array
     */
    protected function AllPurview($request,$menu_id)
    {
        $redis = app('redis.connection');
        $UserLogin=$request->header('UserLogin')?$request->header('UserLogin'):'';
        $GroupId=$request->header('GroupId')?$request->header('GroupId'):'';
        $_purview_id=$redis->GET($UserLogin.'G'.$GroupId.'_purview');
        $res=DB::table('yl_purview')->whereRaw("FIND_IN_SET($menu_id,purview_all)")->where('purview_id',$_purview_id)->first();
        return isset($res->purview_id)?true:false;
    }
}